import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'base_state.dart';
import 'list_state.dart';
import 'refresh_state.dart';
import 'state_widgets.dart';

void main() {
  runApp(
    const ProviderScope(child: MyApp()),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: ProductListPage());
  }
}

/// 使用示例：基础状态管理
class ExampleNotifier extends BaseNotifier<String> {
  @override
  Future<void> loadData() async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));

    // 模拟随机结果
    final random = DateTime.now().millisecond % 3;
    if (random == 0) {
      setEmpty();
    } else if (random == 1) {
      setError('网络连接失败');
    } else {
      setSuccess('加载成功的数据');
    }
  }
}

final exampleProvider =
    StateNotifierProvider<ExampleNotifier, BaseState<String>>(
  (ref) => ExampleNotifier(),
);

class ExamplePage extends ConsumerWidget {
  const ExamplePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(exampleProvider);
    final notifier = ref.read(exampleProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: const Text('基础状态示例')),
      body: StateBuilder<String>(
        state: state,
        onSuccess: (context, data) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('数据: $data'),
                ElevatedButton(
                  onPressed: notifier.refresh,
                  child: const Text('刷新'),
                ),
              ],
            ),
          );
        },
        onRetry: notifier.refresh,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: notifier.loadData,
        child: const Icon(Icons.refresh),
      ),
    );
  }
}

/// 使用示例：列表状态管理
class ProductListNotifier extends ListNotifier<Product> {
  @override
  Future<void> loadData() async {
    await execute(() async {
      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));
      return List.generate(
          10,
          (index) => Product(
                id: index.toString(),
                name: '商品 $index',
                price: (index + 1) * 10.0,
              ));
    });
  }

  @override
  Future<List<Product>> loadMoreData(int page) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));

    // 模拟没有更多数据
    if (page > 3) return [];

    return List.generate(
        5,
        (index) => Product(
              id: '${page}_$index',
              name: '商品 ${page}_$index',
              price: (page * 10 + index + 1) * 10.0,
            ));
  }
}

final productListProvider =
    StateNotifierProvider<ProductListNotifier, ListState<Product>>(
  (ref) => ProductListNotifier(),
);

class ProductListPage extends ConsumerWidget {
  const ProductListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(productListProvider);
    final notifier = ref.read(productListProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: const Text('列表状态示例')),
      body: ListStateBuilder<Product>(
        state: state,
        onSuccess: (context, products) {
          return ListView.builder(
            itemCount: products.length,
            itemBuilder: (context, index) {
              final product = products[index];
              return ListTile(
                title: Text(product.name),
                subtitle: Text('¥${product.price}'),
                trailing: index == products.length - 1 && state.hasMore
                    ? IconButton(
                        icon: const Icon(Icons.add),
                        onPressed: notifier.loadMore,
                      )
                    : null,
              );
            },
          );
        },
        onRetry: notifier.refresh,
        onLoadMore: notifier.loadMore,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: notifier.loadData,
        child: const Icon(Icons.refresh),
      ),
    );
  }
}

/// 使用示例：刷新分页状态管理
class RefreshProductListNotifier extends RefreshNotifier<Product> {
  @override
  Future<(List<Product>, PageInfo)> loadFirstPage() async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));

    final products = List.generate(
        20,
        (index) => Product(
              id: index.toString(),
              name: '商品 $index',
              price: (index + 1) * 10.0,
            ));

    const pageInfo = PageInfo(
      page: 1,
      pageSize: 20,
      total: 100,
      hasMore: true,
    );

    return (products, pageInfo);
  }

  @override
  Future<(List<Product>, PageInfo)> loadNextPage(int page) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));

    // 模拟没有更多数据
    if (page > 5) {
      return (
        [Product(id: "2", name: "sd", price: 12)],
        PageInfo(page: page, hasMore: false)
      );
    }

    final products = List.generate(
        20,
        (index) => Product(
              id: '${page}_$index',
              name: '商品 ${page}_$index',
              price: (page * 20 + index + 1) * 10.0,
            ));

    final pageInfo = PageInfo(
      page: page,
      pageSize: 20,
      total: 100,
      hasMore: page < 5,
    );

    return (products, pageInfo);
  }
}

final refreshProductListProvider =
    StateNotifierProvider<RefreshProductListNotifier, RefreshState<Product>>(
  (ref) => RefreshProductListNotifier(),
);

class RefreshProductListPage extends ConsumerStatefulWidget {
  const RefreshProductListPage({super.key});

  @override
  ConsumerState<RefreshProductListPage> createState() =>
      _RefreshProductListPageState();
}

class _RefreshProductListPageState
    extends ConsumerState<RefreshProductListPage> {
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);

    // 初始化加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(refreshProductListProvider.notifier).initialize();
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      // 距离底部200px时加载更多
      ref.read(refreshProductListProvider.notifier).loadMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(refreshProductListProvider);
    final notifier = ref.read(refreshProductListProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: const Text('刷新分页示例')),
      body: RefreshListBuilder<Product>(
        state: state,
        scrollController: _scrollController,
        onRefresh: notifier.refresh,
        onSuccess: (context, products) {
          return ListView.builder(
            controller: _scrollController,
            itemCount: products.length,
            itemBuilder: (context, index) {
              final product = products[index];
              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  leading: CircleAvatar(
                    child: Text(product.id),
                  ),
                  title: Text(product.name),
                  subtitle: Text('¥${product.price}'),
                  trailing: Text('页面: ${state.pageInfo.page}'),
                ),
              );
            },
          );
        },
        onRetry: notifier.initialize,
        onLoadMore: notifier.loadMore,
      ),
    );
  }
}

/// 数据模型示例
class Product {
  final String id;
  final String name;
  final double price;

  Product({
    required this.id,
    required this.name,
    required this.price,
  });

  @override
  String toString() {
    return 'Product(id: $id, name: $name, price: $price)';
  }
}
